<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * Gpay
 */
class GpayController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['orderId'] = $return['orderid'];
        $data['amount'] = intval($return['amount']*100);
        $data['returnUrl'] = $return['callbackurl'];
        $data['notifyUrl'] = $return['notifyurl'];
        $data['body'] = 'ttt';
		$data['version'] = '1';
        $data['merchantCode'] = $this->config['mch_id'];
        
		$req = $this->getReq($data);
		
		$res = curl($this->config['gateway'], httpstr($req));
		
		$res = json_decode($res, true);
		$data = json_decode(base64_decode(urldecode($res['data'])), true);
		
		if(!$data || empty($data)){
			if($res['msg']){
				$this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
			}
			$this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		
		$tranId = $data['tranId'];
		
		if(!$tranId){
			$this->showmessage('获取ID失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		$data = [];
		$data['merchantCode'] = $this->config['mch_id'];
		$data['tranId'] = $tranId;
		$data['version'] = '1';
		$data['way'] = 'ali_gpay';
		
		$req = $this->getReq($data);
		$res = curl($this->config['appsecret'], httpstr($req));
		
		$res = json_decode($res, true);
		
		//echo '<pre/>'; print_r($data); print_r($res); exit;
		
		$data = json_decode(base64_decode(urldecode($res['data'])), true);
		
		if(!$data || empty($data)){
			if($res['msg']){
				$this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
			}
			$this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		$payParams = json_decode($data['payParams'], true);
		$code = $payParams['codeUrl'];
		
		if(!$code){
			$this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		
		$paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if(isMobile()){
					header("Location:{$code}"); exit;
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }
	
	private function getReq($data){
		$req = [];
		
		$json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
		
		$str = $json . $this->config['signkey'];
		
		$req['sign'] = $this->getSign($json);
		
		$req['data'] = urlencode(base64_encode($json));
		
		return $req;
	}
	
	private function getSign($json){
		return md5($json . $this->config['signkey']);
	}

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", getIP(), FILE_APPEND);
		
		$this->debug_callback();
		
		$p = $origin = I("get.");
		
		/* $p = $origin =  array (
		  'data' => 'eyJ0cmFuSWQiOiI4ZjcyOTQxMS05NWE5LTQ4NTYtYWI1MC04N2M1ZDYxZmQzZTYiLCJhbW91bnQi%0AOjk5OTUsIm9yZGVySWQiOiIyMDE5MDEyMDIwMDg0NTY1NTc3Iiwic3RhdHVzIjoxfQ%3D%3D',
		  'sign' => 'e1b8e1d7b71bb21d57f9b1917518b5d7',
		); */
		
        if(!$p || empty($p)){
            exit("wrong");
        }
		
		$data = $p = json_decode(base64_decode(urldecode($p['data'])), true);
		
		if(!$data || empty($data)){
			exit("data wrong");
		}
		
		/*
		
		Array
		(
			[tranId] => 8f729411-95a9-4856-ab50-87c5d61fd3e6
			[amount] => 9995
			[orderId] => 2019012020084565577
			[status] => 1
		)*/
		
        //获取订单信息
        $orderid = $p['orderId'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            "pay_orderid_rd"=>$p['tranId']
        ));
		
		if($data['status'] != 1){
			exit("pay fail");
		}

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $origin['sign'];
        
		$data = base64_decode(urldecode($origin['data']));
		$sign2 = md5($data . $this->config['signkey']);
		
		
		//echo 'sign: ' . $sign . '<br/>';
		//echo 'sign2: '. $sign2; exit;
        if($sign !== $sign2){
            exit("sign_wrong");
        }

        $this->async($find['pay_orderid'], "{'success':true}");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}